#ifndef _THREAD_h_
#define _THREAD_H_

#include<functional>
#include<cstdio>
#include<pthread.h>
#include"Log.hpp"
#include<atomic>

namespace ThreadModlue
{
    using namespace LogModule;
    static std::atomic<uint32_t> number(1);  // 设置number为原子变量  
    class Thread
    {
        using func_t = std::function<void()>;
    public:
        Thread(func_t func)
        :   _tid(0),
            _isdetach(false),
            _isrunning(false),
            res(nullptr),
            _func(func)
        {
            _name = "thread-" + std::to_string(number++);//  可能引起资源竞争   原子变量保证线程安全
        }

        bool Stop()
        {
            if(_isrunning)
            {
                int n = pthread_cancel(_tid);
                if(n != 0)
                return false;
                else
                {
                    _isrunning = false;
                    return true;
                }
            }
            return false;
        }

        void Join()
        {
            if(_isdetach)
            return ;
            int n = pthread_join(_tid, &res);
            if(n!=0)
            {
                LOG(LogLevel::DEBUG)<<"join线程失败";
            }
            else
            {
                LOG(LogLevel::DEBUG)<<"join线程成功";
            }
        }

        std::string Name()
        {
            return _name;
        }
        
        void Detach()
        {
            if(_isdetach)
                return;
            if(_isrunning)
                pthread_detach(_tid);
            EnableDetach();
        }
        
        bool Start()
        {
            if(_isrunning)
            return false;
            int n = pthread_create(&_tid, nullptr, Routine, this);
            if(n != 0)
            {
                return false;
            }
            else 
            {
                return true;
            }
        }
        pthread_t Id()
        {
            return _tid;
        }
        ~Thread()
        {
        }
    private:
        void EnableDetach()
        {
            _isdetach = true;
        }
        void EnableRunning()
        {
            _isrunning = true;
        }
        static void* Routine(void* args)
        {
            Thread* self = static_cast<Thread*>(args);
            self->EnableRunning();
            if(self->_isdetach)
            {
                self->Detach();
            }
            pthread_setname_np(self->_tid, self->_name.c_str());
            self->_func();
            return nullptr;
        }

        pthread_t _tid;
        std::string _name;
        bool _isdetach;
        bool _isrunning;
        void *res;
        func_t _func;
    };
}
#endif